import { Router } from "express";
import { MongoDBService } from "../services/mongodb-service";

const router = Router();

// MongoDB 服务实例
const mongoService = new MongoDBService();

// 获取wxapp用户列表（分页/搜索）
router.get("/wxapp-users", async (req, res) => {
  try {
    const { 
      page = 1, 
      pageSize = 20, 
      search = '', 
      status = '' 
    } = req.query;

    const pageNum = parseInt(page as string);
    const size = parseInt(pageSize as string);
    
    // 获取所有用户（使用MongoDB服务）
    const users = await mongoService.getAllWxUsers();

    // 搜索和状态过滤
    let filteredUsers = users;
    if (search) {
      const searchTerm = (search as string).toLowerCase();
      filteredUsers = users.filter(user => 
        (user.phone && user.phone.includes(searchTerm)) || 
        user.nickname.toLowerCase().includes(searchTerm)
      );
    }
    if (status) {
      filteredUsers = filteredUsers.filter(user => user.status === status);
    }

    // 排序（最新注册的在前）
    filteredUsers.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());

    // 分页
    const total = filteredUsers.length;
    const startIndex = (pageNum - 1) * size;
    const endIndex = startIndex + size;
    const paginatedUsers = filteredUsers.slice(startIndex, endIndex);

    // 格式化返回数据
    const formattedUsers = paginatedUsers.map(user => ({
      id: user.id,
      phone: user.phone,
      nickname: user.nickname,
      avatar: user.avatar,
      status: user.status,
      roles: user.roles,
      createdAt: user.createdAt,
      updatedAt: user.updatedAt,
      lastLoginAt: user.lastLoginAt
    }));

    return res.json({
      success: true,
      data: {
        users: formattedUsers,
        pagination: {
          page: pageNum,
          pageSize: size,
          total,
          totalPages: Math.ceil(total / size)
        }
      }
    });

  } catch (error: any) {
    console.error("获取wxapp用户列表错误:", error);
    return res.status(500).json({
      success: false,
      message: "服务器内部错误"
    });
  }
});

// 获取单个wxapp用户详情
router.get("/wxapp-users/:id", async (req, res) => {
  try {
    const { id } = req.params;
    
    const user = await mongoService.getWxUserById(id);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: "用户不存在"
      });
    }

    return res.json({
      success: true,
      data: {
        id: user.id,
        phone: user.phone,
        nickname: user.nickname,
        avatar: user.avatar,
        status: user.status,
        roles: user.roles,
        createdAt: user.createdAt,
        updatedAt: user.updatedAt,
        lastLoginAt: user.lastLoginAt
      }
    });

  } catch (error: any) {
    console.error("获取wxapp用户详情错误:", error);
    return res.status(500).json({
      success: false,
      message: "服务器内部错误"
    });
  }
});

// 更新wxapp用户信息（冻结/解冻、改昵称等）
router.patch("/wxapp-users/:id", async (req, res) => {
  try {
    const { id } = req.params;
    const { status, nickname } = req.body;

    const user = await mongoService.getWxUserById(id);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: "用户不存在"
      });
    }

    const updateData: any = {};
    const changes: string[] = [];

    // 更新状态
    if (status && ['active', 'frozen'].includes(status)) {
      if (user.status !== status) {
        updateData.status = status;
        changes.push(`状态: ${status === 'active' ? '激活' : '冻结'}`);

        // 如果冻结用户，删除其所有 refresh token
        if (status === 'frozen') {
          await mongoService.deleteWxRefreshTokensByUserId(id);
        }
      }
    }

    // 更新昵称
    if (nickname && nickname.trim()) {
      const newNickname = nickname.trim();
      if (user.nickname !== newNickname) {
        updateData.nickname = newNickname;
        changes.push(`昵称: ${newNickname}`);
      }
    }

    if (Object.keys(updateData).length === 0) {
      return res.status(400).json({
        success: false,
        message: "没有需要更新的内容"
      });
    }

    // 更新用户信息
    updateData.updatedAt = new Date();
    const updatedUser = await mongoService.updateWxUser(id, updateData);

    console.log(`[管理员操作] 更新wxapp用户 ${user.phone}: ${changes.join(', ')}`);

    return res.json({
      success: true,
      message: "用户信息更新成功",
      data: {
        id: user.id,
        phone: user.phone,
        nickname: user.nickname,
        avatar: user.avatar,
        status: user.status,
        roles: user.roles,
        updatedAt: user.updatedAt
      }
    });

  } catch (error: any) {
    console.error("更新wxapp用户错误:", error);
    return res.status(500).json({
      success: false,
      message: "服务器内部错误"
    });
  }
});

// 获取wxapp用户登录审计
router.get("/wxapp-users/:id/logins", async (req, res) => {
  try {
    const { id } = req.params;
    
    const user = await mongoService.getWxUserById(id);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: "用户不存在"
      });
    }

    // TODO: 实际项目中应该从日志系统或数据库获取登录记录
    // 这里返回模拟数据
    const mockLoginHistory = [
      {
        id: 1,
        loginTime: user.lastLoginAt || user.createdAt,
        ip: '192.168.1.100',
        device: 'iPhone 13',
        location: '北京市朝阳区',
        success: true
      }
    ];

    return res.json({
      success: true,
      data: {
        userId: user.id,
        phone: user.phone,
        loginHistory: mockLoginHistory
      }
    });

  } catch (error: any) {
    console.error("获取wxapp用户登录审计错误:", error);
    return res.status(500).json({
      success: false,
      message: "服务器内部错误"
    });
  }
});

// 批量操作wxapp用户
router.post("/wxapp-users/batch", async (req, res) => {
  try {
    const { action, userIds } = req.body;

    if (!action || !Array.isArray(userIds) || userIds.length === 0) {
      return res.status(400).json({
        success: false,
        message: "操作类型和用户ID列表不能为空"
      });
    }

    if (!['freeze', 'unfreeze'].includes(action)) {
      return res.status(400).json({
        success: false,
        message: "不支持的操作类型"
      });
    }

    const results = {
      success: 0,
      failed: 0,
      details: [] as any[]
    };

    for (const userId of userIds) {
      const user = await mongoService.getWxUserById(userId);
      if (!user) {
        results.failed++;
        results.details.push({
          userId,
          success: false,
          message: "用户不存在"
        });
        continue;
      }

      const newStatus = action === 'freeze' ? 'frozen' : 'active';
      if (user.status === newStatus) {
        results.details.push({
          userId,
          success: true,
          message: `用户已经是${newStatus === 'frozen' ? '冻结' : '激活'}状态`
        });
        continue;
      }

      await mongoService.updateWxUser(userId, {
        status: newStatus,
        updatedAt: new Date()
      });

      // 如果冻结用户，删除其所有 refresh token
      if (newStatus === 'frozen') {
        await mongoService.deleteWxRefreshTokensByUserId(userId);
      }

      results.success++;
      results.details.push({
        userId,
        success: true,
        message: `用户${newStatus === 'frozen' ? '冻结' : '解冻'}成功`
      });
    }

    console.log(`[管理员批量操作] ${action}: 成功${results.success}个, 失败${results.failed}个`);

    return res.json({
      success: true,
      message: `批量操作完成: 成功${results.success}个, 失败${results.failed}个`,
      data: results
    });

  } catch (error: any) {
    console.error("批量操作wxapp用户错误:", error);
    return res.status(500).json({
      success: false,
      message: "服务器内部错误"
    });
  }
});

export default router;